/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package backing.beans;

import commonBackingBean.RoleBean;
import entities.Student;
import entities.TeacherAdmin;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
import sessionBeans.StudentFacadeLocal;
import sessionBeans.TeacherAdminFacadeLocal;
import tools.StaticFields;
import tools.User;
import org.jasypt.util.password.StrongPasswordEncryptor;

/**
 *
 * @author myPC
 */
@Named
@SessionScoped
public class CheckLogin implements Serializable {

    @Inject
    private RoleBean roleBean;
    @EJB
    private StudentFacadeLocal studentFacadeLocal;
    @EJB
    private TeacherAdminFacadeLocal teacherAdminFacadeLocal;

    private User user;
    private String username, password, welcomeMess;
    private String rand;
    private int tryTime = 0;
    private boolean logined = false, rendered = true;
    private final int tryTimeLimitedNumber = 3;
    private int roleType = StaticFields.STUDENT_ROLE;
    private final HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);

    private boolean isUserlegal(String name, String password) {
        boolean result = false;
        if (getRoleType() == StaticFields.STUDENT_ROLE) {
            List<Student> studentsList = studentFacadeLocal.getQueryResultList("select * from student where name='" + name + "'");
            if (null != studentsList && studentsList.size() > 0) {
                result = this.isValidUser(password, studentsList.get(0).getPassword());
                if (result) {
                    session.setAttribute(StaticFields.STUDENTREF, studentsList.get(0));
                }
            }

        } else if (getRoleType() == StaticFields.TEACHER_ROLE || getRoleType() == StaticFields.ADMIN_ROLE) {
            List<TeacherAdmin> teacherAdminList = teacherAdminFacadeLocal.getQueryResultList("select * from TEACHER_ADMIN where name='" + name + "'");
            if (null != teacherAdminList && teacherAdminList.size() > 0) {
                result = this.isValidUser(password, teacherAdminList.get(0).getPassword());
                if (result) {
                    session.setAttribute(StaticFields.TEACHERREF, teacherAdminList.get(0));
                }
            }
        }
        return result;
    }

    public String validateUser() {
//        String genRand = ((String) session.getAttribute("rand")).trim();
        if (!FacesContext.getCurrentInstance().getMessageList().isEmpty()) {
            FacesContext.getCurrentInstance().getMessageList().clear();
        }
        if (tryTime++ < tryTimeLimitedNumber) {//尝试登录未超过规定次数
            //  if (genRand.equals(this.rand)) {//验证码正确
            if (isUserlegal(this.username, this.password)) {//用户存在
                session.setAttribute(StaticFields.LOGIN_ROLE, this.getRoleType());
                session.setAttribute("myUser", this.getUser());
                session.setAttribute("userno", this.username);
                this.welcomeMess = this.getUser().getName();
                tryTime = 0;
                this.logined = true;
                return StaticFields.MAIN_PAGE;
                // return;
            } else {//用户名或密码错误
                FacesContext.getCurrentInstance().addMessage("loginButton", new FacesMessage(StaticFields.MESSAGES_PROPTES.getString("ivalidUP")));
                this.rand = null;
                this.password = null;
                return null;
            }
//            } else {//验证码错误
//                this.rand = null;
//                this.password = null;
//                FacesContext.getCurrentInstance().addMessage("validatorCode", new FacesMessage(StaticFields.MESSAGES_PROPTES.getString("invValiCode")));
//                return null;
//            }
        } else {
            this.rendered = false;
            FacesContext.getCurrentInstance().addMessage("loginButton", new FacesMessage(StaticFields.MESSAGES_PROPTES.getString("tryFaild")));
            this.rand = null;
            this.password = null;
            return null;
        }
    }

    public String submit() {//注册
        //判断是学生还是教师，如果是教师，则选择Teacher表，否则选择Student表
        if (this.getRoleType() == StaticFields.STUDENT_ROLE) {
            Student student = new Student();
            student.setEmail(this.getUser().getEmail());
            student.setFirstname(this.getUser().getFirstName());
            student.setSecondname(this.getUser().getSecondName());
            student.setName(this.getUser().getName());
            student.setPassword(this.encrypt(this.getUser().getPassword()));
            studentFacadeLocal.create(student);
        } else if (this.getRoleType() == StaticFields.TEACHER_ROLE || this.getRoleType() == StaticFields.ADMIN_ROLE) {
            TeacherAdmin teacherAdmin = new TeacherAdmin();
            teacherAdmin.setEmail(this.getUser().getEmail());
            teacherAdmin.setFirstname(this.getUser().getFirstName());
            teacherAdmin.setSecondname(this.getUser().getSecondName());
            teacherAdmin.setName(this.getUser().getName());
            teacherAdmin.setPassword(this.encrypt(this.getUser().getPassword()));
            teacherAdminFacadeLocal.create(teacherAdmin);
        }
        return null;
    }

    public String login(int loginType) {
        this.setRoleType(loginType);
        return StaticFields.LONGIN_PATH;
    }

    public String logout() {
        this.user = null;
        this.username = null;
        this.logined = false;
        this.password = null;
        this.roleType = 0;
        session.invalidate();
        return StaticFields.NOLOGIN_MAIN_PAGE;
    }

    public String register() {
        return StaticFields.REGISTER_PATH;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @param rand the rand to set
     */
    public void setRand(String rand) {
        this.rand = rand;
    }

    public String getRand() {
        return this.rand;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return this.password;
    }

    /**
     * @return the welcomeMess
     */
    public String getWelcomeMess() {
        return welcomeMess;
    }

    /**
     * @return the rendered
     */
    public boolean isLogined() {
        return logined;
    }

    /**
     * @param rendered the rendered to set
     */
    public void setLogined(boolean rendered) {
        this.logined = rendered;
    }

    /**
     * @return the rendered
     */
    public boolean isRendered() {
        return rendered;
    }

    /**
     * @param rendered the rendered to set
     */
    public void setRendered(boolean rendered) {
        this.rendered = rendered;
    }

    /**
     * @return the user
     */
    public User getUser() {
        if (null == user) {
            return new User();
        }
        return user;
    }

    /**
     * @return the userType
     */
    public int getUserType() {
        return getRoleType();
    }

    /**
     * @param userType the userType to set
     */
    public void setUserType(int userType) {
        this.setRoleType(userType);
    }

    /**
     * @return the r oleType
     */
    public int getRoleType() {
        return roleType;
    }

    /**
     * @param roleType the roleType to set
     */
    public void setRoleType(int roleType) {
        this.roleType = roleType;
    }

    public String getRoleinfo() {
        return StaticFields.MESSAGES_PROPTES.getString(roleBean.getRoleinfo(this.roleType).getRolename());
    }

    StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();

    private boolean isValidUser(String inputPassword, String encryptedPassword) {
        if (passwordEncryptor.checkPassword(inputPassword, encryptedPassword)) {
            return true;
        } else {
            return false;
        }
    }

    private String encrypt(String password) {
        return passwordEncryptor.encryptPassword(password);
        //Then put encryptedPassword into database.
    }
}
